package com.controller;

import com.beans.DeviceEntity;
import com.beans.ErrorStatusEnum;
import com.beans.FileManageEntity;
import com.common.entity.R;
import com.common.utils.UploadFileUtil;
import com.repository.DeviceRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author gm
 * @description 设备详情CRUD
 * @date 2020/5/29
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("device")
public class DeviceController {

    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private DeviceRepository deviceRepository;

    @Resource
    private UploadFileUtil uploadFileUtil;

    /**
     * 获取所有设备详情
     *
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @GetMapping("getDevice")
    public R getDevice() {
        List<DeviceEntity> resultList = deviceRepository.findAll();
        Object total = entityManager.createNativeQuery("select count(id) from device").getSingleResult();
        R ok = R.ok();
        ok.put("rows", resultList);
        ok.put("total", total);
        return ok;
    }

    /**
     * 分页获取设备详情，可根据需求传入不同数量的参数
     * <p>
     * 需要分页的话 page rows 必须都传入
     * 需要排序的话，请至少传入排序字段，默认升序
     *
     * @param state      设备状态( 0.删除 1.正常)
     * @param categoryId 设备类别id
     * @param situation  设备租售情况( 1.出租 2.出售 3.既出租又出售)
     * @param page       第几页
     * @param rows       每页几条数据
     * @param sort       排序字段名
     * @param order      排序方式  asc desc
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @GetMapping("getDevicePage")
    public R getDevicePage(Integer state, Integer categoryId, Integer situation, Integer page, Integer rows, String sort, String order) {
        //region 组装hql
        StringBuilder sql = new StringBuilder("select * from device where 1 = 1 ");
        StringBuilder countSql = new StringBuilder("select count(id) from device where 1 = 1 ");
        if (state != null) {
            sql.append(" and state = :state ");
            countSql.append(" and state = :state ");
        }
        if (categoryId != null) {
            sql.append(" and categoryId = :categoryId ");
            countSql.append(" and categoryId = :categoryId ");
        }
        if (situation != null) {
            if (1 == situation || 2 == situation) {
                sql.append(" and (situation = 3 or situation = :situation) ");
                countSql.append(" and (situation = 3 or situation = :situation) ");
            }
        }
        if (!StringUtils.isEmpty(sort)) {
            sql.append(" order by ").append(sort).append(" ");
            if (!StringUtils.isEmpty(order)) {
                sql.append(order);
            }
        }
        if (page != null && rows != null) {
            sql.append(" limit :offset , :rows ");
        }
        //endregion 组装hql
        //region 组装查询对象和参数
        Query query = entityManager.createNativeQuery(sql.toString(), DeviceEntity.class);
        Query queryCount = entityManager.createNativeQuery(countSql.toString());
        if (state != null) {
            query.setParameter("state", state);
            queryCount.setParameter("state", state);
        }
        if (categoryId != null) {
            query.setParameter("categoryId", categoryId);
            queryCount.setParameter("categoryId", categoryId);
        }
        if (situation != null) {
            if (1 == situation || 2 == situation) {
                query.setParameter("situation", situation);
                queryCount.setParameter("situation", situation);
            }
        }
        if (page != null && rows != null) {
            query.setParameter("offset", (page - 1) * rows).setParameter("rows", rows);
        }

        List<DeviceEntity> resultList = query.getResultList();
        Object count = queryCount.getSingleResult();
        R ok = R.ok();
        ok.put("total", count);
        ok.put("rows", resultList);
        return ok;

    }

    /**
     * 新增/修改设备
     *
     * @param device
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @PostMapping("saveOrUpdateDevice")
    public R saveOrUpdateDevice(@Valid DeviceEntity device) {
        device.setUpdateTime(new Date());
        List<FileManageEntity> list = entityManager.createNativeQuery("select * from file_manage where deviceId=?", FileManageEntity.class).setParameter(1, device.getId()).getResultList();
        device.setDevicePicture(list);
        device = entityManager.merge(device);
        return R.ok(device);
    }

    /**
     * 删除设备
     *
     * @param ids
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @PostMapping("deleteDevice")
    public R deleteDevice(@RequestParam(value = "ids[]") List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), "删除操作，id不能为空!");
        }
        entityManager.createNativeQuery("update device set state = 0 where id in :id").setParameter("id", ids).executeUpdate();
        return R.ok();
    }

    /**
     * 根据设备id获取设备所有图片
     *
     * @param deviceId 设备id
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/1
     */
    @GetMapping("getPicture")
    public R getPicture(Integer deviceId) {
        List list = entityManager.createQuery("from FileManageEntity where state = 1 and deviceId = :deviceId").setParameter("deviceId", deviceId).getResultList();
        return R.ok(list);
    }

    /**
     * 上传设备主图
     *
     * @param files 上传的图片
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @PostMapping("uploadPicture")
    public R uploadPicture(Integer deviceId, @RequestParam(value = "files") MultipartFile[] files) {
        List paths = new ArrayList<>();
        if (deviceId == null) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), "请传入要关联设备的id");
        }
        if (files == null || files.length <= 0) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), "请添加上传文件");
        }
        for (MultipartFile file : files) {
            //类型3为设备主图
            String fileType = "3";
            R r = uploadFileUtil.uploadPicture(file, fileType);
            if (ErrorStatusEnum.OK.code().equals(r.get(R.CODE))) {
                //文件访问url
                String url = (String) r.get(R.DATA);
                paths.add(r.get(R.DATA));
                //组装FileManageEntity信息并保存到数据库
                String fileOldName = file.getOriginalFilename();
                FileManageEntity fileManage = new FileManageEntity();
                fileManage.setCreateTime(new Date());
                fileManage.setState(1);
                fileManage.setFileName(url.substring(url.lastIndexOf("/") + 1));
                fileManage.setFileType(3);
                fileManage.setUrl(url);
                fileManage.setDeviceId(deviceId);
                fileManage.setFileOldName(fileOldName);
                entityManager.merge(fileManage);
            } else {
                return r.put("uploadSuccess", paths);
            }

        }
        return R.ok();
    }

    /**
     * 删除设备图片
     *
     * @param ids
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @PostMapping("deletePicture")
    public R deletePicture(@RequestParam(value = "ids[]") List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), "删除操作，id不能为空!");
        }
        entityManager.createNativeQuery("update file_manage set state = 0 where id in :id").setParameter("id", ids).executeUpdate();
        return R.ok();
    }

    /**
     * 模糊查询设备详情
     *
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @GetMapping("getDeviceLikeName")
    public R getDeviceLikeName(String name) {
        if(StringUtils.isEmpty(name)){
            return R.ok();
        }
        List<DeviceEntity> resultList = entityManager.createQuery("from DeviceEntity where state = 1 and name like :name", DeviceEntity.class).setParameter("name", "%"+name+"%")
                .setMaxResults(100).getResultList();
        return R.ok(resultList);
    }
}
